package org.sixtynine.stock.dao.impl;

/**
 * @author Thilan
 *
 */

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.sixtynine.stock.Constants;
import org.sixtynine.stock.dao.UserDao;
import org.sixtynine.stock.dto.GridPramDTO;
import org.sixtynine.stock.dto.Page;
import org.sixtynine.stock.entity.User;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl extends AbstractDaoImpl<User, Integer> implements
		UserDao {

	protected UserDaoImpl() {
		super(User.class);
	}

	@Override
	public void saveUser(User user) {
		saveOrUpdate(user);
	}

	@Override
	public List<User> findUser(String name) {
		return findByCriteria(Restrictions.like("name", name, MatchMode.START));
	}

	@Override
	public User findUserByUserName(String userName) {
		List<User> users = findByCriteria(Restrictions.eq("userName", userName));
		if (users.size() > 0) {
			return users.get(0);
		} else {
			return null;
		}
	}

	@Override
	public List<User> searchUser(int categoryId) {
		Criteria criteria = getCurrentSession().createCriteria(
				User.class);

		if (categoryId > Constants.ERROR) {
			criteria.add(Restrictions.eq("userCategory.id", categoryId));
		}
		
		return findByCriteria(criteria);
	}

	@Override
	public Page<User> searchUser(int categoryId,
			GridPramDTO gridPramDTO) {
		Criteria criteria = getCurrentSession().createCriteria(
				User.class);

		if (categoryId > Constants.ERROR) {
			criteria.add(Restrictions.eq("userCategory.id", categoryId));
		}
		return findByCriteria(criteria, gridPramDTO);
	}

	@Override
	public boolean isEmailExist(String email) {
		List<User> users = findByCriteria(Restrictions.eq("email", email));
		if (users.size() > 0) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean isUserExist(String userName) {
		List<User> users = findByCriteria(Restrictions.eq("userName", userName));
		if (users.size() > 0) {
			return true;
		} else {
			return false;
		}
	}

}
